// utils/validator.ts
interface ValidationRule {
  required?: boolean;
  min?: number;
  max?: number;
  minLength?: number;
  maxLength?: number;
  pattern?: RegExp;
  validator?: (value: any) => boolean | string; // 返回true或错误消息
  message?: string; // 默认错误消息
}

interface ValidationResult {
  isValid: boolean;
  message?: string;
}

class Validator {
  /**
   * 验证单个值
   * @param value 要验证的值
   * @param rules 验证规则数组
   * @returns ValidationResult
   */
  validate(value: any, rules: ValidationRule[]): ValidationResult {
    for (const rule of rules) {
      // 1. 必填项验证
      if (rule.required && (value === null || value === undefined || (typeof value === 'string' && value.trim() === ''))) {
        return { isValid: false, message: rule.message || '此项为必填项' };
      }
      // 如果不是必填项且值为空，则无需进行后续验证
      if (!rule.required && (value === null || value === undefined || (typeof value === 'string' && value.trim() === ''))) {
        continue;
      }

      // 2. 最小/最大值（数字）
      if (typeof value === 'number') {
        if (rule.min !== undefined && value < rule.min) {
          return { isValid: false, message: rule.message || `值不能小于${rule.min}` };
        }
        if (rule.max !== undefined && value > rule.max) {
          return { isValid: false, message: rule.message || `值不能大于${rule.max}` };
        }
      }

      // 3. 最小/最大长度（字符串或数组）
      if (typeof value === 'string' || Array.isArray(value)) {
        if (rule.minLength !== undefined && value.length < rule.minLength) {
          return { isValid: false, message: rule.message || `长度不能少于${rule.minLength}个字符` };
        }
        if (rule.maxLength !== undefined && value.length > rule.maxLength) {
          return { isValid: false, message: rule.message || `长度不能超过${rule.maxLength}个字符` };
        }
      }

      // 4. 正则表达式匹配
      if (rule.pattern && !rule.pattern.test(value)) {
        return { isValid: false, message: rule.message || '格式不正确' };
      }

      // 5. 自定义验证器
      if (rule.validator) {
        const customResult = rule.validator(value);
        if (typeof customResult === 'boolean' && !customResult) {
          return { isValid: false, message: rule.message || '验证失败' };
        }
        if (typeof customResult === 'string') {
          return { isValid: false, message: customResult }; // 自定义返回错误消息
        }
      }
    }
    return { isValid: true };
  }

  /**
   * 验证一个表单对象
   * @param formData 表单数据对象，例如 { name: '张三', phone: '123...' }
   * @param validationSchema 验证规则模式，例如 { name: [{ required: true }], phone: [{ pattern: /^1\d{10}$/, message: '手机号格式不正确' }] }
   * @returns Record<string, ValidationResult> 包含每个字段的验证结果
   */
  validateForm<T extends Record<string, any>>(formData: T, validationSchema: { [K in keyof T]?: ValidationRule[] }): { [K in keyof T]?: ValidationResult } {
    const errors: { [K in keyof T]?: ValidationResult } = {};
    let allValid = true;

    for (const key in validationSchema) {
      if (Object.prototype.hasOwnProperty.call(validationSchema, key)) {
        const rules = validationSchema[key]!;
        const value = formData[key];
        const result = this.validate(value, rules);
        if (!result.isValid) {
          errors[key] = result;
          allValid = false;
        }
      }
    }
    return errors;
  }
}

export const validator = new Validator();

// 使用示例：
// const userSchema = {
//   username: [
//     { required: true, message: '用户名不能为空' },
//     { minLength: 2, maxLength: 10, message: '用户名长度2-10' }
//   ],
//   email: [
//     { required: true, message: '邮箱不能为空' },
//     { pattern: /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/, message: '邮箱格式不正确' }
//   ],
//   age: [
//     { validator: (val: number) => val >= 18, message: '必须年满18岁' }
//   ]
// };

// const formData = {
//   username: 'john',
//   email: 'test@example.com',
//   age: 20
// };

// const errors = validator.validateForm(formData, userSchema);
// console.log(errors); // { isValid: true } 或者具体的错误信息